<template>
  <div class="mod-config editViewContainer">
    <split-pane class="splitPane" :min-percent='10' :default-percent='10' split="vertical">
      <template slot="paneL">
        <div class="treeViewContainer">
          <tree-view ref="treeView" :treeData="statusTreeList" :checkChangedHandler="getDataList"></tree-view>
        </div>
      </template>
      <template slot="paneR">
        <table-view ref="view"
                    :searchAttrs="searchAttrs"
                    :primaryKey="primaryKey"
                    :listApiName="listApiName"
                    :deleteApiName="deleteApiName"
                    :saveAuthName="saveAuthName"
                    :deleteAuthName="deleteAuthName"
                    :showAttrs="showAttrs"
                    :exportAuthName="exportAuthName"
                    :exportPlantFunc="exportPlantFunc"
        >
        </table-view>
      </template>
    </split-pane>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog
      title="制定商品采购合同"
      :visible="purchaseContractVisible"
      width="70%">

      <el-form
        ref="dataForm"
        label-width="120px"
        label-position="left"
        style="margin-left:30px"
      >

        <el-form-item label="供应商" style="width: 400px">
          <el-select v-model="supplierId" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label=采购时间 style="width: 400px">
          <el-date-picker
            v-model="contractTime"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label=交货时间 style="width: 400px">
          <el-date-picker
            v-model="deliveryTime"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label=总金额 style="width: 400px">
          <el-input-number controls-position="right" size="small" :min="0"  v-model="totalAmount"  disabled placeholder="数量"></el-input-number>
        </el-form-item>
        <el-form-item label=付款周期>
          <el-radio-group v-model="paymentCycle" >
            <el-radio :label="0" border>月结</el-radio>
            <el-radio :label="1" border>款到发货</el-radio>
            <el-radio :label="2" border>3个月账期</el-radio>
            <el-radio :label="3" border>付30%定金，余款70%款到发货</el-radio>
            <el-radio :label="4" border>2个月账期</el-radio>

          </el-radio-group>
        </el-form-item>

      </el-form>

      <el-table
        :data="tableListData"
        border
        style="display: inline-block">
        <el-table-column
          prop="id"
          label="订单编号"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.orderDetailId" clearable filterable placeholder="请选择"  >
              <el-option
                v-for="item in orderDetailList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>


        <el-table-column
          prop="id"
          label="商品信息"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.productId" clearable filterable placeholder="请选择"  >
              <el-option
                v-for="item in sysDictList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="unitPrice"
          label="单价"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0" @change="calculateTotalAmount"  v-model="scope.row.unitPrice"  placeholder="价格"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="purchaseNumber"
          label="数量"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0" @change="calculateTotalAmount"  v-model="scope.row.purchaseNumber"  placeholder="数量"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="taxInclusive"
          label="是否含税"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.taxInclusive">
              <el-radio :label=0>不含</el-radio>
              <el-radio :label=1>含税</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>

        <el-table-column
          prop="customerRequire"
          label="规格描述"
          align="center"
        >
          <template slot-scope="scope">
            <el-input  size="small"  v-model="scope.row.customerRequire"  placeholder="规格描述"></el-input>
          </template>
        </el-table-column>

        <el-table-column
          prop="supplierProductNo"
          label="供应商产品编号"
          align="center"
        >
          <template slot-scope="scope">
              <el-input  size="small"  v-model="scope.row.supplierProductNo"  placeholder="供应商产品编号"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        >
          <template slot-scope="scope">
            <el-input type="textarea" controls-position="right" size="small" :min="0"  v-model="scope.row.remark" placeholder="备注"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="purchaseContractVisible = false">取 消</el-button>
        <el-button type="primary" @click=savePurchaseContractAndUpdatePartStatus>确 定</el-button>
      </span>

    </el-dialog>
  </div>
</template>


<script>
import tableView from '@/components/tableView'
import basicMixins from '@/utils/commonViewMixins'
import AddOrUpdate from './purchasepart-add-or-update'
import treeView from '@/components/treeView'
import {mRequest} from '@/utils/request'
import {exportHandle, isAuth} from '@/utils'

export default {
  mixins: [basicMixins],
  data() {
    return {
      statusTreeList: [],
      primaryKey: 'id',
      listApiName: 'purchaseApi/listPurchasePartList',
      deleteApiName: 'purchaseApi/deletePurchasePart',
      saveAuthName: 'purchase:purchasepart:save',
      deleteAuthName: 'purchase:purchasepart:delete',
      exportAuthName: 'purchase:purchasepart:save',
      searchAttrs: {
        clientContractNo: {
          placeholder: '请输入业务合同号',
        },
        productNo: {
          placeholder: '请输入商品编号',
        },
        createUser: {
          label: '业务',
          clearable: true,
          type: 'autoComplete',
          placeholder: '请选择申请人',
          querySearchApiName: 'systemApi/listSaleUser'
        },
        supplierId: {
          label: '供应商名称',
          clearable: true,
          type: 'autoComplete',
          placeholder: '请输入供应商名称',
          querySearchApiName: 'supplierApi/getSupplierList'
        },
        dateTimeRange: {
          type: 'date',
          dateType: 'daterange',
          clearable: true
        },
        productCategoryId: {
          type: 'func',
          dataFunc: () => {
            return '1'
          }
        },
        status: {
          type: 'func',
          dataFunc: () => {
            return this.$refs.treeView.$refs.treeForm.getCheckedKeys()[0]
          }
        }
      },
      showAttrs: {
        supplierName: {
          label: '供应商',
          width: 140,
        },
        userName:{
          label: '申请人'
        },
        clientContractNo: {
          label: '业务合同',
          width: 140,
        },
        productNo: {
          label: '商品信息',
          width: 140,
          type: 'linkLabel',
          searchKey: 'productNo',
          routerName: 'product-product-info-all'
        },
        customerRequire:{
          label: '规格描述',
          width: 170
        },
        businessRemark: {
          label: '业务订单备注',
          width: 200
        },
        remark: {
          label: '备注',
          width: 200
        },
        // supplierProductNo:{
        //   label: '供应商产品编号',
        //   width: 140,
        // },
        productWeight:{
          label: '克重'
        },
        productVolume: {label: '容量'},
        unitPrice: {
          label: '价格'
        },
        taxInclusive: {
          label: '含税价',
          type: 'radio',
          items: [
            {value: 0, text: '不含税'},
            {value: 1, text: '含税'}
          ]
        },
        sampleImage: {label: '采购图片', type: 'image'},
        purchaseNumber: {
          label: '采购数量'
        },
        putInStorageNumber:{
          label: '入库数量'
        },

        status: {
          label: '状态',
          type: 'radio',
          items: [
            {value: 0, text: '待采购', tagType: 'info'},
            {value: 2, text: '采购进行中'},
            {value: 3, text: '采购逾期预警',tagType:'warning'},
            {value: 4, text: '采购已逾期', tagType: 'danger'},
            {value: 5, text: '货已完工'},
            {value: 6, text: '采购暂停', tagType: 'info'},
            {value: 7, text: '入库进行中',tagType: 'warning'},
            {value: 8, text: '入库完成',tagType: 'success'},
            {value: 17, text: '挑选', tagType: 'warning'},
            {value: 18, text: '合格', tagType: 'success'},
            {value: 19, text: '不合格', tagType: 'danger'},
            {value: 20, text: '特采', tagType: 'warning'},
            {value: 99, text: '采购取消', tagType: 'danger'},
          ]
        },
        createTime: {
          label: '采购时间',
          type: 'date', width: 100
        },
        purchaseEndTime: {
          label: '交货时间',
          type: 'date', width: 100
        },
        imagePath: {
          label: '图片', type: 'image'
        },
        contractPurchaseNo: {
          label: '采购合同',
          type: 'linkLabel',
          routerName: 'contract-contractpurchaseinfo',
          searchKey: 'purchaseContractNo'
        }
      },
      purchaseContractVisible: false,
      supplierList: [],
      sysDictList: [],
      orderDetailList: [],
      supplierId: '',
      contractTime: '',
      deliveryTime: '',
      paymentCycle: '',
      totalAmount: 0,
      purchaseType: 14,
      remark: '',
      tableListData: [],
    }
  },
  components: {
    treeView,
    tableView,
    AddOrUpdate
  },
  methods: {
    calculateTotalAmount() {
      this.totalAmount=0
      for (let i = 0; i <this.tableListData.length ; i++) {
        this.tableListData[i].totalPrice = this.tableListData[i].unitPrice * this.tableListData[i].purchaseNumber
        this.totalAmount += this.tableListData[i].totalPrice
      }
    },

    statusTreeListInit() {
      mRequest('systemApi/getPurchaseStatusList', {}, (res) => {
        this.statusTreeList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    // TODO 待晚上只有采购状态为0可以下单
    exportPlantFunc(rows){
      this.supplierId = ''
      this.contractTime = ''
      this.deliveryTime = ''
      this.paymentCycle = ''
      this.purchaseType = 14
      this.remark = ''
      this.purchaseContractVisible = true
      this.initOrderDetailList()
      this.initSupplierList()
      this.initSysDictList()
      this.tableListData = rows
      this.calculateTotalAmount()
    },
    initSupplierList() {
      mRequest('supplierApi/getSupplierList', {}, (res) => {
        this.supplierList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initOrderDetailList() {
      mRequest('orderApi/getOrderDetailList', {}, (res) => {
        this.orderDetailList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initSysDictList() {
      mRequest('productApi/getProductInfoList', {}, (res) => {
        this.sysDictList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    savePurchaseContractAndUpdatePartStatus(){
      if (this.R.isNil(this.supplierId) || this.R.isEmpty(this.supplierId)) {
        this.$message.error('请选择供应商')
        return
      }
      if (this.R.isNil(this.contractTime) || this.R.isEmpty(this.contractTime)) {
        this.$message.error('请选择合同时间')
        return
      }
      if (this.R.isNil(this.deliveryTime) || this.R.isEmpty(this.deliveryTime)) {
        this.$message.error('请选择交货时间')
        return
      }
      mRequest('contractApi/savePurchaseContractAndUpdatePartStatus', {
        'supplierId': this.supplierId,
        'contractTime': this.contractTime,
        'deliveryTime': this.deliveryTime,
        'purchaseType': this.purchaseType,
        'paymentCycle': this.paymentCycle,
        'totalAmount': this.totalAmount,
        'tableListDataBottleCap': this.tableListData
      }, (res => {
        let data = res.data
        if (data && data.code == 0) {
          let contractPurchaseInfo=data.contractPurchaseInfo
          this.$confirm('是否直接导出改计划?', '提示', {
            confirmButtonText: '导出',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            exportHandle('contractApi/getPurchasePartContractExport', {'contractPurchaseId': contractPurchaseInfo.id})
          }).catch(() => {
          })
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.purchaseContractVisible = false
              this.getDataList()
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      }))
    }
  },
  mounted() {
    this.statusTreeListInit()
  }
}
</script>
